import {I18N_LANGUAGE_KEY} from '@/i18n'
import axios from 'axios'
import {message, Modal} from 'ant-design-vue';
import {useStore} from "@/store/user";
import {useRouter} from "vue-router";
import router from "@/router";


const controller = new AbortController()
export const cancel = (reason: any) => controller.abort(reason)

export const request = axios.create({
    baseURL: process.env.NODE_ENV === 'development' ? '' : process.env.VUE_APP_DEV_API,
    signal: controller.signal,
    withCredentials: true,
})


request.interceptors.request.use(
    function (config) {
        if(process.env.NODE_ENV === 'production') {
            let url = config.url;
            config.url=url.replace(/^\/api/, '')
        }
        config.headers ??= {}
        config.headers['Language'] = localStorage.getItem(I18N_LANGUAGE_KEY)
        return config
    },
    function (error) {
        return Promise.reject(error)
    }
)


request.interceptors.response.use(
    function (response) {
        if (response.data.code == 200) {

            return response;

        } else if (response.data.code == 400) {

            message.error(response.data.errMsg)

        } else if (response.data.code == 401) {

            message.error(response.data.errMsg,2)
            useStore().removeUser();
            window.location.reload()
        }

        return Promise.reject(response.data)
    },
    function (error) {
        return Promise.reject(error)
    }
)

const toLogin=()=>{
   router.push({
        name: "login",
   });
}

export interface APIResponse<T = any> {
    data: APIResult<T>
}

export interface APIResult<T = any> {
    code?: string
    errMsg?: string
    pageData?: T
    total?: number
}
